﻿using JujuyASPNET.SourceCodeFormatter;
using Wolfpack.Core.Interfaces.Entities;
using Wolfpack.Core.Interfaces.Magnum;
using Wolfpack.Core.Publishers;
using Omu.ValueInjecter;

namespace Wolfpack.Contrib.Publishers.Email
{
    public class EmailPublisher : PublisherBase, INotificationEventPublisher
    {
        protected readonly EmailConfiguration _config;

        public EmailPublisher(EmailConfiguration config)
        {
            _config = config;

            Enabled = config.Enabled;
            FriendlyId = config.FriendlyId;
        }

        public void Consume(NotificationEvent notification)
        {
            var smtpUtility = new HtmlSmtpUtility(_config);
            var model = MapNotificationToModel(notification);
            smtpUtility.Send(model);
        }

        private static NotificationModel MapNotificationToModel(NotificationEvent notification)
        {          
            var formatter = new JavaScriptCode
            {
                EmbedStyleSheet = true,
                InLineStyle = true
            };

            var model = new NotificationModel();
            model.InjectFrom<LoopValueInjection>(notification, 
                new
                {
                    Data = formatter.FormatCode(notification.Data),
                    Result = notification.Result.GetValueOrDefault(),
                    ResultCount = notification.ResultCount.GetValueOrDefault(),
                    Info = notification.Message
                });

            return model;
        }
    }
}